<template>
  <div class="outing-container">
    <div class="header-section">
      <h2>外出记录管理</h2>
      <button class="primary-button" @click="showAddDialog">
        <i class="icon-plus"></i>
        新增外出记录
      </button>
    </div>

    <!-- 查询和筛选区域 -->
    <div class="filter-section card">
      <div class="filter-row">
        <div class="filter-item">
          <label>老人姓名:</label>
          <input 
            v-model="searchForm.elderName" 
            placeholder="请输入老人姓名" 
            type="text"
            @keyup.enter="filterRecords"
            class="filter-input"
          />
        </div>
        <div class="filter-item">
          <label>状态:</label>
          <select v-model="searchForm.status" @change="filterRecords" class="filter-select">
            <option value="">全部</option>
            <option value="外出">外出</option>
            <option value="回归">回归</option>
          </select>
        </div>
        <div class="filter-actions">
          <button class="search-button" @click="filterRecords">
            <i class="icon-search"></i>
            查询
          </button>
          <button class="reset-button" @click="resetFilter">
            <i class="icon-refresh"></i>
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 数据展示区域 -->
    <div class="tabs card">
      <div 
        class="tab" 
        :class="{ active: activeTab === 'all' }" 
        @click="switchTab('all')"
      >
        全部记录
      </div>
      <div 
        class="tab" 
        :class="{ active: activeTab === '外出' }" 
        @click="switchTab('外出')"
      >
        外出 ({{ getStatusCount('外出') }})
      </div>
      <div 
        class="tab" 
        :class="{ active: activeTab === '回归' }" 
        @click="switchTab('回归')"
      >
        回归 ({{ getStatusCount('回归') }})
      </div>
    </div>

    <div class="table-container card">
      <table class="data-table">
        <thead>
          <tr>
            <th>记录ID</th>
            <th>老人姓名</th>
            <th>状态</th>
            <th>记录时间</th>
            <th>返回时间</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="record in filteredRecords" :key="record.recordId">
            <td>{{ record.recordId }}</td>
            <td>{{ record.elderName }}</td>
            <td>
              <span :class="['status-badge', record.direction]">
                {{ record.direction }}
              </span>
            </td>
            <td>{{ record.recordTime }}</td>
            <td>{{ record.returnTime || '-' }}</td>
            <td>{{ record.notes || '-' }}</td>
            <td>
              <div class="action-buttons">
                <button class="action-button edit" @click="editRecord(record)">
                  <i class="icon-edit"></i>
                  编辑
                </button>
                <button class="action-button delete" @click="deleteRecord(record.recordId)">
                  <i class="icon-delete"></i>
                  删除
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="filteredRecords.length === 0">
            <td colspan="7" class="empty-row">
              <div class="empty-state">
                <i class="icon-empty"></i>
                <p>暂无数据</p>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑外出记录对话框 -->
    <div v-if="dialogVisible" class="dialog-overlay">
      <div class="dialog">
        <div class="dialog-header">
          <h3>{{ dialogTitle }}</h3>
          <button class="close-button" @click="dialogVisible = false">
            <i class="icon-close"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="form-group" v-if="!isEdit">
            <label>选择老人:</label>
            <select v-model="addForm.elderId" @change="handleElderChange" class="form-select">
              <option value="">请选择老人</option>
              <option 
                v-for="elder in elders" 
                :key="elder.elderId" 
                :value="elder.elderId"
              >
                {{ elder.name }}
              </option>
            </select>
          </div>
          
          <div class="form-group" v-else>
            <label>老人姓名:</label>
            <input 
              v-model="editForm.elderName" 
              type="text"
              disabled
              class="form-input"
            />
          </div>
          
          <div class="form-group">
            <label>状态:</label>
            <select v-model="commonForm.direction" class="form-select">
              <option value="外出">外出</option>
              <option value="回归">回归</option>
            </select>
          </div>
          
          <div class="form-group" v-if="!isEdit">
            <label>记录时间:</label>
            <input 
              v-model="addForm.recordTime" 
              type="datetime-local" 
              class="form-input"
            />
          </div>
          
          <div class="form-group" v-else>
            <label>返回时间:</label>
            <input 
              v-model="editForm.returnTime" 
              type="datetime-local" 
              class="form-input"
            />
          </div>
          
          <div class="form-group">
            <label>备注:</label>
            <textarea 
              v-model="commonForm.notes" 
              placeholder="请输入备注"
              class="form-textarea"
            ></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="dialogVisible = false" class="cancel-button">
            取消
          </button>
          <button class="primary-button" @click="saveRecord">
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import request from '../../utils/request'

const outingRecords = ref([])
const elders = ref([]) // 老人列表
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const activeTab = ref('all')

// 搜索表单
const searchForm = ref({
  elderName: '',
  status: ''
})

// 新增表单
const addForm = ref({
  elderId: null,
  elderName: '',
  recordTime: ''
})

// 编辑表单
const editForm = ref({
  recordId: null,
  elderName: '',
  returnTime: ''
})

// 公共表单字段
const commonForm = ref({
  direction: '外出',
  notes: ''
})

// 过滤后的记录
const filteredRecords = computed(() => {
  let result = [...outingRecords.value]
  
  // 根据搜索条件过滤
  if (searchForm.value.elderName) {
    result = result.filter(record => 
      record.elderName && record.elderName.includes(searchForm.value.elderName)
    )
  }
  
  if (searchForm.value.status) {
    result = result.filter(record => 
      record.direction === searchForm.value.status
    )
  }
  
  // 根据标签页过滤
  if (activeTab.value !== 'all') {
    result = result.filter(record => 
      record.direction === activeTab.value
    )
  }
  
  return result
})

// 获取指定状态的记录数量
const getStatusCount = (status) => {
  return outingRecords.value.filter(record => record.direction === status).length
}

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab
}

// 过滤记录
const filterRecords = () => {
  // 过滤逻辑在 computed 属性中处理
}

// 重置筛选条件
const resetFilter = () => {
  searchForm.value.elderName = ''
  searchForm.value.status = ''
  activeTab.value = 'all'
}

// 获取外出记录列表
const fetchOutingRecords = async () => {
  try {
    const res = await request.get('/outing/get')
    if (res.code === 1) {
      outingRecords.value = res.data
      console.log('获取外出记录:', res.data);
    }
  } catch (error) {
    console.error('获取外出记录失败:', error)
    alert('获取外出记录失败')
  }
}

// 获取社区老人列表
const fetchElders = async () => {
  try {
    const res = await request.get('/community/elderList')
    if (res.code === 1) {
      elders.value = res.data
    }
  } catch (error) {
    console.error('获取老人列表失败:', error)
    alert('获取老人列表失败')
  }
}

// 处理选择老人的变更
const handleElderChange = (event) => {
  const elderId = parseInt(event.target.value)
  const selectedElder = elders.value.find(elder => elder.elderId === elderId)
  if (selectedElder) {
    addForm.value.elderName = selectedElder.name
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '新增外出记录'
  isEdit.value = false
  
  // 重置表单
  addForm.value = {
    elderId: null,
    elderName: '',
    recordTime: ''
  }
  
  commonForm.value = {
    direction: '外出',
    notes: ''
  }
  
  dialogVisible.value = true
}

// 编辑记录
const editRecord = (record) => {
  dialogTitle.value = '编辑外出记录'
  isEdit.value = true
  
  // 填充表单数据
  editForm.value = {
    recordId: record.recordId,
    elderName: record.elderName,
    returnTime: record.returnTime || ''
  }
  
  commonForm.value = {
    direction: record.direction,
    notes: record.notes
  }
  
  dialogVisible.value = true
}

// 保存记录（新增或更新）
const saveRecord = async () => {
  try {
    // 验证必填字段
    if (!isEdit.value) {
      // 新增验证
      if (!addForm.value.elderId) {
        alert('请选择老人')
        return
      }
      
      if (!addForm.value.recordTime) {
        alert('请选择记录时间')
        return
      }
    } else {
      // 编辑验证
      if (!editForm.value.returnTime) {
        alert('请选择返回时间')
        return
      }
    }
    
    if (!isEdit.value) {
      // 新增记录
      const addDTO = {
        elderId: addForm.value.elderId,
        elderName: addForm.value.elderName,
        direction: commonForm.value.direction,
        recordTime: addForm.value.recordTime,
        notes: commonForm.value.notes
      }
      
      console.log('发送新增数据:', addDTO);
      
      const res = await request.post('/outing/add', addDTO)
      if (res.code === 1) {
        alert('添加成功')
        dialogVisible.value = false
        fetchOutingRecords()
      } else {
        alert(res.msg || '添加失败')
      }
    } else {
      // 更新记录
      const updateDTO = {
        recordId: editForm.value.recordId,
        direction: commonForm.value.direction,
        returnTime: editForm.value.returnTime,
        notes: commonForm.value.notes
      }
      
      console.log('发送更新数据:', updateDTO);
      
      const res = await request.put('/outing/update', updateDTO)
      if (res.code === 1) {
        alert('更新成功')
        dialogVisible.value = false
        fetchOutingRecords()
      } else {
        alert(res.msg || '更新失败')
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    console.error('错误详情:', error.response?.data || error);
    alert('保存失败: ' + (error.message || ''))
  }
}

// 删除记录
const deleteRecord = async (recordId) => {
  if (confirm('确定要删除这条记录吗？')) {
    // 注意：后端没有提供删除接口，这里只是在前端移除
    const index = outingRecords.value.findIndex(record => record.recordId === recordId)
    if (index !== -1) {
      outingRecords.value.splice(index, 1)
      alert('删除成功')
    }
  }
}

onMounted(() => {
  fetchOutingRecords()
  fetchElders()
})
</script>

<style scoped>
.outing-container {
  padding: 24px;
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f2ff 100%);
  min-height: calc(100vh - 70px);
}

.header-section {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-section h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.primary-button {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.primary-button:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 24px;
}

.filter-section {
  padding: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.filter-input,
.filter-select {
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  min-width: 180px;
  transition: all 0.3s;
}

.filter-input:focus,
.filter-select:focus {
  border-color: #40a9ff;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.filter-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 1px;
}

.search-button,
.reset-button {
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
}

.search-button {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  box-shadow: 0 2px 4px rgba(79, 172, 254, 0.2);
}

.search-button:hover {
  background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(79, 172, 254, 0.3);
}

.reset-button {
  background-color: #fff;
  border: 1px solid #d9d9d9;
  color: rgba(0, 0, 0, 0.65);
}

.reset-button:hover {
  background-color: #f5f5f5;
  transform: translateY(-2px);
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  padding: 0;
  margin-bottom: 20px;
}

.tab {
  padding: 16px 24px;
  cursor: pointer;
  font-weight: 500;
  color: #666;
  border-bottom: 3px solid transparent;
  transition: all 0.3s;
  position: relative;
}

.tab.active {
  color: #4facfe;
  border-bottom: 3px solid #4facfe;
}

.tab:hover {
  color: #4facfe;
  background-color: #f9f9f9;
}

.table-container {
  padding: 0;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 16px 20px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.data-table th {
  background-color: #fafafa;
  font-weight: 600;
  color: #555;
  font-size: 14px;
}

.data-table tbody tr:hover {
  background-color: #f9f9f9;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.外出 {
  background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
  color: #856404;
}

.status-badge.回归 {
  background: linear-gradient(135deg, #e8f7ef 0%, #d0f0e0 100%);
  color: #28a745;
}

.action-button {
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  transition: all 0.3s;
  border: none;
  min-height: 32px;
  min-width: 64px;
  line-height: 1;
}

.action-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
  height: 100%;
}

.action-button.edit {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  box-shadow: 0 2px 4px rgba(79, 172, 254, 0.2);
}

.action-button.edit:hover {
  background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(79, 172, 254, 0.3);
}

.action-button.delete {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
  color: white;
  box-shadow: 0 2px 4px rgba(255, 107, 107, 0.2);
}

.action-button.delete:hover {
  background: linear-gradient(135deg, #ff8e8e 0%, #ff6b6b 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(255, 107, 107, 0.3);
}

.empty-row {
  text-align: center;
  padding: 60px 20px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: #999;
}

.empty-state i {
  font-size: 48px;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background-color: #fff;
  border-radius: 8px;
  width: 520px;
  max-width: 90%;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e8e8e8;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: white;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.close-button:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.dialog-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
  transition: all 0.3s;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  border-color: #40a9ff;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-textarea {
  min-height: 100px;
  resize: vertical;
}

.dialog-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-button {
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  color: rgba(0, 0, 0, 0.65);
  transition: all 0.3s;
}

.cancel-button:hover {
  background-color: #f5f5f5;
  transform: translateY(-2px);
}

/* 图标样式 */
.icon-plus::before,
.icon-search::before,
.icon-refresh::before,
.icon-edit::before,
.icon-delete::before,
.icon-close::before,
.icon-empty::before {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

@media (max-width: 768px) {
  .outing-container {
    padding: 16px;
  }
  
  .header-section {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .filter-input,
  .filter-select {
    min-width: auto;
  }
  
  .data-table {
    font-size: 13px;
  }
  
  .data-table th,
  .data-table td {
    padding: 12px 10px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 5px;
  }
  
  .action-button {
    justify-content: center;
  }
}
</style>